<template>
  <div class="font-inter bg-gray-light text-dark min-h-screen flex flex-col">
    <div class="flex flex-1 overflow-hidden">
      <!-- 主内容区 -->
      <main class="flex-1 overflow-y-auto p-4 lg:p-6 bg-gray-light">
        <!-- 页面标题 -->
        <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
          <div>
            <h1 class="text-2xl font-bold text-dark mb-1">仪表盘</h1>
            <p class="text-gray-medium">实时监控生产状态和关键指标</p>
          </div>

          <div class="mt-4 md:mt-0 flex space-x-3">
            <div class="relative">
              <select
                v-model="dateRange"
                class="pl-4 pr-10 py-2 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all appearance-none bg-white"
              >
                <option>今日</option>
                <option>本周</option>
                <option>本月</option>
                <option>本季度</option>
                <option>本年度</option>
              </select>
              <i
                class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-medium pointer-events-none"
              ></i>
            </div>

            <button
              @click="refreshData"
              class="flex items-center px-4 py-2 bg-white border border-gray-200 rounded-lg text-dark hover:bg-gray-50 transition-colors"
            >
              <i class="fa fa-refresh mr-2"></i>
              <span>刷新</span>
            </button>

            <button
              @click="exportReport"
              class="flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shadow-sm"
            >
              <i class="fa fa-download mr-2"></i>
              <span>导出报告</span>
            </button>
          </div>
        </div>

        <!-- 数据概览卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
          <div class="bg-white rounded-xl shadow-card p-5 transform hover:scale-[1.02] transition-transform duration-300">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-gray-medium font-medium">今日产量</h3>
              <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                <i class="fa fa-cubes text-primary"></i>
              </div>
            </div>
            <div class="flex items-end justify-between">
              <div>
                <p class="text-3xl font-bold text-dark">28,543</p>
                <p class="text-xs text-secondary flex items-center mt-1">
                  <i class="fa fa-arrow-up mr-1"></i> 12.5% <span class="text-gray-medium ml-1">较昨日</span>
                </p>
              </div>
              <div class="h-16 w-24">
                <canvas id="chart1"></canvas>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5 transform hover:scale-[1.02] transition-transform duration-300">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-gray-medium font-medium">设备利用率</h3>
              <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center">
                <i class="fa fa-industry text-warning"></i>
              </div>
            </div>
            <div class="flex items-end justify-between">
              <div>
                <p class="text-3xl font-bold text-dark">82.7%</p>
                <p class="text-xs text-danger flex items-center mt-1">
                  <i class="fa fa-arrow-down mr-1"></i> 3.2% <span class="text-gray-medium ml-1">较昨日</span>
                </p>
              </div>
              <div class="h-16 w-24">
                <canvas id="chart2"></canvas>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5 transform hover:scale-[1.02] transition-transform duration-300">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-gray-medium font-medium">质量合格率</h3>
              <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center">
                <i class="fa fa-check-circle text-secondary"></i>
              </div>
            </div>
            <div class="flex items-end justify-between">
              <div>
                <p class="text-3xl font-bold text-dark">98.3%</p>
                <p class="text-xs text-secondary flex items-center mt-1">
                  <i class="fa fa-arrow-up mr-1"></i> 0.5% <span class="text-gray-medium ml-1">较昨日</span>
                </p>
              </div>
              <div class="h-16 w-24">
                <canvas id="chart3"></canvas>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5 transform hover:scale-[1.02] transition-transform duration-300">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-gray-medium font-medium">工单完成率</h3>
              <div class="w-10 h-10 rounded-full bg-info/10 flex items-center justify-center">
                <i class="fa fa-calendar-check-o text-info"></i>
              </div>
            </div>
            <div class="flex items-end justify-between">
              <div>
                <p class="text-3xl font-bold text-dark">76.8%</p>
                <p class="text-xs text-secondary flex items-center mt-1">
                  <i class="fa fa-arrow-up mr-1"></i> 5.3% <span class="text-gray-medium ml-1">较昨日</span>
                </p>
              </div>
              <div class="h-16 w-24">
                <canvas id="chart4"></canvas>
              </div>
            </div>
          </div>
        </div>

        <!-- 主要图表区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
          <div class="bg-white rounded-xl shadow-card p-5 lg:col-span-2">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">产量趋势分析</h3>
              <div class="flex space-x-2">
                <button @click="setTrendPeriod('day')" class="px-3 py-1 text-xs rounded-md bg-primary/10 text-primary">日</button>
                <button @click="setTrendPeriod('week')" class="px-3 py-1 text-xs rounded-md hover:bg-gray-light">周</button>
                <button @click="setTrendPeriod('month')" class="px-3 py-1 text-xs rounded-md hover:bg-gray-light">月</button>
                <button @click="setTrendPeriod('quarter')" class="px-3 py-1 text-xs rounded-md hover:bg-gray-light">季</button>
              </div>
            </div>
            <div class="h-80">
              <canvas id="productionTrendChart"></canvas>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">产品类别分布</h3>
              <button class="text-gray-medium hover:text-primary">
                <i class="fa fa-ellipsis-v"></i>
              </button>
            </div>
            <div class="h-80">
              <canvas id="productCategoryChart"></canvas>
            </div>
          </div>
        </div>

        <!-- 设备状态和工单进度 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
          <div class="bg-white rounded-xl shadow-card p-5">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">设备状态</h3>
              <div class="flex items-center text-xs text-primary">
                <span class="inline-block w-2 h-2 rounded-full bg-primary mr-1"></span>
                <span>实时更新</span>
              </div>
            </div>

            <div class="space-y-4">
              <div
                v-for="(equipment, index) in equipmentList"
                :key="index"
                class="p-4 border border-gray-100 rounded-lg hover:border-primary/30 hover:bg-primary/5 transition-all cursor-pointer"
              >
                <div class="flex items-center justify-between">
                  <div class="flex items-center">
                    <div
                      class="w-10 h-10 rounded-full"
                      :class="{
                        'bg-secondary/10': equipment.status === 'running',
                        'bg-warning/10': equipment.status === 'maintenance',
                        'bg-danger/10': equipment.status === 'fault',
                        'bg-gray-200': equipment.status === 'standby'
                      }"
                    >
                      <i
                        class="fa"
                        :class="{
                          'fa-check text-secondary': equipment.status === 'running',
                          'fa-exclamation-triangle text-warning': equipment.status === 'maintenance',
                          'fa-times text-danger': equipment.status === 'fault',
                          'fa-clock-o text-gray-medium': equipment.status === 'standby'
                        }"
                      ></i>
                    </div>
                    <div>
                      <h5 class="font-medium text-dark">{{ equipment.name }}</h5>
                      <p class="text-xs text-gray-medium">设备编号: {{ equipment.code }}</p>
                    </div>
                  </div>
                  <span
                    class="px-2 py-1 text-xs rounded-full"
                    :class="{
                      'bg-secondary/10 text-secondary': equipment.status === 'running',
                      'bg-warning/10 text-warning': equipment.status === 'maintenance',
                      'bg-danger/10 text-danger': equipment.status === 'fault',
                      'bg-gray-100 text-gray-medium': equipment.status === 'standby'
                    }"
                  >
                    {{ equipment.statusText }}
                  </span>
                </div>
                <div class="mt-3">
                  <div class="flex items-center justify-between mb-1">
                    <span class="text-xs text-gray-medium">利用率</span>
                    <span class="text-xs font-medium text-dark">{{ equipment.utilization }}%</span>
                  </div>
                  <div class="w-full bg-gray-100 rounded-full h-2">
                    <div
                      class="h-2 rounded-full"
                      :class="{
                        'bg-secondary': equipment.status === 'running',
                        'bg-warning': equipment.status === 'maintenance',
                        'bg-gray-200': equipment.status === 'fault' || equipment.status === 'standby'
                      }"
                      :style="{ width: equipment.utilization + '%' }"
                    ></div>
                  </div>
                </div>
                <div class="mt-2 flex items-center text-xs text-gray-medium">
                  <span class="flex items-center mr-3" v-if="equipment.runningTime">
                    <i class="fa fa-clock-o text-gray-medium mr-1"></i>
                    运行时间: {{ equipment.runningTime }}
                  </span>
                  <span class="flex items-center" v-if="equipment.powerConsumption">
                    <i class="fa fa-bolt text-warning mr-1"></i>
                    能耗: {{ equipment.powerConsumption }}
                  </span>
                  <span class="flex items-center" v-if="equipment.nextMaintenance">
                    <i class="fa fa-wrench text-primary mr-1"></i>
                    下次维护: {{ equipment.nextMaintenance }}
                  </span>
                  <span class="flex items-center" v-if="equipment.maintenancePerson">
                    <i class="fa fa-user-o text-danger mr-1"></i>
                    维修人员: {{ equipment.maintenancePerson }}
                  </span>
                  <span class="flex items-center" v-if="equipment.plannedStart">
                    <i class="fa fa-calendar text-primary mr-1"></i>
                    计划启动: {{ equipment.plannedStart }}
                  </span>
                </div>
              </div>
            </div>

            <button
              @click="viewAllEquipment"
              class="w-full mt-4 py-2 text-sm text-primary hover:text-primary/80 transition-colors"
            >
              查看全部设备 <i class="fa fa-angle-right ml-1"></i>
            </button>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5 lg:col-span-2">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">工单进度跟踪</h3>
              <div class="flex space-x-2">
                <button @click="setWorkOrderPeriod('day')" class="px-3 py-1 text-xs rounded-md bg-primary/10 text-primary">
                  今日
                </button>
                <button @click="setWorkOrderPeriod('week')" class="px-3 py-1 text-xs rounded-md hover:bg-gray-light">本周</button>
                <button @click="setWorkOrderPeriod('month')" class="px-3 py-1 text-xs rounded-md hover:bg-gray-light">
                  本月
                </button>
              </div>
            </div>

            <div class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="bg-gray-50 text-left">
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">工单编号</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">产品名称</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">计划数量</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">完成率</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">预计完成</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">负责人</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">状态</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                  <tr v-for="(workOrder, index) in workOrders" :key="index" class="hover:bg-gray-50 transition-colors">
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="font-medium text-dark">{{ workOrder.number }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="font-medium text-dark">{{ workOrder.productName }}</div>
                      <div class="text-xs text-gray-medium">{{ workOrder.customer }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="text-dark">{{ workOrder.plannedQuantity }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="w-full bg-gray-100 rounded-full h-2.5">
                        <div
                          class="h-2.5 rounded-full"
                          :class="{
                            'bg-warning': workOrder.status === 'inProgress',
                            'bg-secondary': workOrder.status === 'completed',
                            'bg-primary': workOrder.status === 'pending',
                            'bg-danger': workOrder.status === 'overdue'
                          }"
                          :style="{ width: workOrder.completionRate + '%' }"
                        ></div>
                      </div>
                      <div class="text-xs text-dark mt-1">{{ workOrder.completionRate }}%</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="text-dark">{{ workOrder.expectedCompletion }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="flex items-center">
                        <div class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center mr-2">
                          <span class="text-xs text-dark">{{ workOrder.leaderInitial }}</span>
                        </div>
                        <span class="text-sm text-dark">{{ workOrder.leader }}</span>
                      </div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <span
                        class="px-2 py-1 text-xs rounded-full"
                        :class="{
                          'bg-warning/10 text-warning': workOrder.status === 'inProgress',
                          'bg-secondary/10 text-secondary': workOrder.status === 'completed',
                          'bg-primary/10 text-primary': workOrder.status === 'pending',
                          'bg-danger/10 text-danger': workOrder.status === 'overdue'
                        }"
                      >
                        {{ workOrder.statusText }}
                      </span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <button
              @click="viewAllWorkOrders"
              class="w-full mt-4 py-2 text-sm text-primary hover:text-primary/80 transition-colors"
            >
              查看全部工单 <i class="fa fa-angle-right ml-1"></i>
            </button>
          </div>
        </div>

        <!-- 质量分析和物料库存 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
          <div class="bg-white rounded-xl shadow-card p-5">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">质量分析</h3>
              <button class="text-gray-medium hover:text-primary">
                <i class="fa fa-ellipsis-v"></i>
              </button>
            </div>

            <div class="h-64">
              <canvas id="qualityAnalysisChart"></canvas>
            </div>

            <div class="mt-4 space-y-3">
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <div class="w-3 h-3 rounded-full bg-secondary mr-2"></div>
                  <span class="text-sm text-dark">合格</span>
                </div>
                <span class="text-sm font-medium text-dark">98.3%</span>
              </div>

              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <div class="w-3 h-3 rounded-full bg-warning mr-2"></div>
                  <span class="text-sm text-dark">返工</span>
                </div>
                <span class="text-sm font-medium text-dark">1.2%</span>
              </div>

              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <div class="w-3 h-3 rounded-full bg-danger mr-2"></div>
                  <span class="text-sm text-dark">报废</span>
                </div>
                <span class="text-sm font-medium text-dark">0.5%</span>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5 lg:col-span-2">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">物料库存预警</h3>
              <div class="flex space-x-2">
                <button @click="setInventoryView('low')" class="px-3 py-1 text-xs rounded-md bg-primary/10 text-primary">
                  库存不足
                </button>
                <button @click="setInventoryView('all')" class="px-3 py-1 text-xs rounded-md hover:bg-gray-light">
                  所有物料
                </button>
              </div>
            </div>

            <div class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="bg-gray-50 text-left">
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">物料编码</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">物料名称</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">规格型号</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">当前库存</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">安全库存</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">预计到货</th>
                    <th class="px-5 py-3 text-xs font-semibold text-gray-medium uppercase tracking-wider">操作</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                  <tr v-for="(material, index) in filteredMaterials" :key="index" class="hover:bg-gray-50 transition-colors">
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="font-medium text-dark">{{ material.code }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="font-medium text-dark">{{ material.name }}</div>
                      <div class="text-xs text-gray-medium">{{ material.specification }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="text-dark">{{ material.standard }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div
                        :class="{
                          'text-danger font-medium': material.current < material.safety,
                          'text-warning font-medium': material.current < material.safety * 1.2,
                          'text-dark': material.current >= material.safety * 1.2
                        }"
                      >
                        {{ material.current }}
                      </div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="text-dark">{{ material.safety }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <div class="text-dark">{{ material.expectedArrival || "-" }}</div>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">
                      <button
                        @click="handleMaterialAction(material)"
                        :class="{
                          'text-primary hover:text-primary/80 text-sm': material.current < material.safety * 1.2,
                          'text-primary hover:text-primary/80 text-sm': material.current >= material.safety * 1.2
                        }"
                      >
                        {{ material.current < material.safety * 1.2 ? "紧急采购" : "查看详情" }}
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <button
              @click="viewAllMaterials"
              class="w-full mt-4 py-2 text-sm text-primary hover:text-primary/80 transition-colors"
            >
              查看全部物料 <i class="fa fa-angle-right ml-1"></i>
            </button>
          </div>
        </div>

        <!-- 近期通知和任务 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div class="bg-white rounded-xl shadow-card p-5">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">近期通知</h3>
              <button class="text-gray-medium hover:text-primary">
                <i class="fa fa-ellipsis-v"></i>
              </button>
            </div>

            <div class="space-y-4">
              <div
                v-for="(notice, index) in notices"
                :key="index"
                class="p-3"
                :class="{
                  'border-l-4 border-primary bg-primary/5 rounded-r-lg': notice.type === 'primary',
                  'border-l-4 border-warning bg-warning/5 rounded-r-lg': notice.type === 'warning',
                  'border-l-4 border-secondary bg-secondary/5 rounded-r-lg': notice.type === 'secondary',
                  'border-l-4 border-danger bg-danger/5 rounded-r-lg': notice.type === 'danger'
                }"
              >
                <div class="flex items-start justify-between">
                  <div>
                    <h5 class="font-medium text-dark">{{ notice.title }}</h5>
                    <p class="text-sm text-gray-medium mt-1">{{ notice.content }}</p>
                  </div>
                  <span class="text-xs text-gray-medium">{{ notice.date }}</span>
                </div>
              </div>
            </div>

            <button @click="viewAllNotices" class="w-full mt-4 py-2 text-sm text-primary hover:text-primary/80 transition-colors">
              查看全部通知 <i class="fa fa-angle-right ml-1"></i>
            </button>
          </div>

          <div class="bg-white rounded-xl shadow-card p-5 lg:col-span-2">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-dark">待办任务</h3>
              <button
                @click="createNewTask"
                class="flex items-center px-3 py-1 text-xs rounded-md bg-primary text-white hover:bg-primary/90 transition-colors"
              >
                <i class="fa fa-plus mr-1"></i> 新建任务
              </button>
            </div>

            <div class="space-y-3">
              <div
                v-for="(task, index) in tasks"
                :key="index"
                class="p-3 border border-gray-100 rounded-lg hover:border-primary/30 hover:bg-primary/5 transition-all"
              >
                <div class="flex items-start justify-between">
                  <div class="flex">
                    <div class="mt-1 mr-3">
                      <input
                        type="checkbox"
                        :checked="task.completed"
                        @change="toggleTaskCompletion(task)"
                        class="w-5 h-5 rounded border-gray-300 text-primary focus:ring-primary"
                      />
                    </div>
                    <div>
                      <h5 class="font-medium text-dark">{{ task.title }}</h5>
                      <p class="text-sm text-gray-medium mt-1">{{ task.description }}</p>
                      <div class="flex items-center mt-2 text-xs text-gray-medium">
                        <span class="flex items-center mr-4">
                          <i class="fa fa-calendar text-primary mr-1"></i>
                          截止日期: {{ task.dueDate }}
                        </span>
                        <span class="flex items-center">
                          <i class="fa fa-user-o text-primary mr-1"></i>
                          负责人: {{ task.assignee }}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="flex flex-col items-end">
                    <span
                      class="px-2 py-1 text-xs rounded-full"
                      :class="{
                        'bg-warning/10 text-warning': task.priority === 'high',
                        'bg-info/10 text-info': task.priority === 'medium',
                        'bg-gray-100 text-gray-medium': task.priority === 'low'
                      }"
                    >
                      {{ task.priorityText }}
                    </span>
                    <div class="mt-2 flex space-x-2">
                      <button class="text-primary hover:text-primary/80 text-xs">
                        <i class="fa fa-pencil"></i>
                      </button>
                      <button class="text-danger hover:text-danger/80 text-xs">
                        <i class="fa fa-trash-o"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <button @click="viewAllTasks" class="w-full mt-4 py-2 text-sm text-primary hover:text-primary/80 transition-colors">
              查看全部任务 <i class="fa fa-angle-right ml-1"></i>
            </button>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { Chart, registerables } from "chart.js"; // 修改导入方式

// 注册所有 Chart.js 组件
Chart.register(...registerables);
// 状态管理
ref(false);
ref("");
const dateRange = ref("今日");
const trendPeriod = ref("day");
const workOrderPeriod = ref("day");
const inventoryView = ref("low");

// 数据
const equipmentList = ref([
  {
    name: "冷镦机 LD-24",
    code: "EQ-001",
    status: "running",
    statusText: "运行中",
    utilization: 95,
    runningTime: "7.5h",
    powerConsumption: "120kW"
  },
  {
    name: "搓丝机 CS-12",
    code: "EQ-005",
    status: "maintenance",
    statusText: "需要维护",
    utilization: 78,
    nextMaintenance: "2天后",
    powerConsumption: "85kW"
  },
  {
    name: "热处理炉 HT-300",
    code: "EQ-012",
    status: "fault",
    statusText: "故障",
    utilization: 0,
    maintenancePerson: "王师傅 (处理中)"
  },
  {
    name: "镀锌生产线 ZX-50",
    code: "EQ-018",
    status: "standby",
    statusText: "待机",
    utilization: 0,
    plannedStart: "2025-06-08 08:00"
  }
]);

const workOrders = ref([
  {
    number: "WO-20250601-001",
    productName: "高强度六角螺栓 M12",
    customer: "上海汽车集团",
    plannedQuantity: "10,000件",
    completionRate: 68,
    expectedCompletion: "2025-06-12",
    leader: "李师傅",
    leaderInitial: "李",
    status: "inProgress",
    statusText: "生产中"
  },
  {
    number: "WO-20250602-002",
    productName: "不锈钢螺母 M8",
    customer: "广东电器有限公司",
    plannedQuantity: "25,000件",
    completionRate: 100,
    expectedCompletion: "2025-06-05",
    leader: "王师傅",
    leaderInitial: "王",
    status: "completed",
    statusText: "已完成"
  },
  {
    number: "WO-20250603-003",
    productName: "平垫圈 10",
    customer: "江苏机械制造",
    plannedQuantity: "50,000件",
    completionRate: 25,
    expectedCompletion: "2025-06-10",
    leader: "赵师傅",
    leaderInitial: "赵",
    status: "pending",
    statusText: "待排产"
  },
  {
    number: "WO-20250528-004",
    productName: "内六角圆柱头螺钉 M6",
    customer: "浙江电子科技",
    plannedQuantity: "8,000件",
    completionRate: 90,
    expectedCompletion: "2025-06-05",
    leader: "刘师傅",
    leaderInitial: "刘",
    status: "overdue",
    statusText: "逾期"
  }
]);

const materials = ref([
  {
    code: "MAT-2025007",
    name: "高强度线材",
    specification: "中碳钢 φ10mm",
    standard: "GB/T 699-2015",
    current: "3.2吨",
    safety: "5吨",
    expectedArrival: "2025-06-05"
  },
  {
    code: "MAT-2025012",
    name: "镀锌添加剂",
    specification: "环保型",
    standard: "HJ/T 253-2006",
    current: "15kg",
    safety: "20kg",
    expectedArrival: "2025-06-07"
  },
  {
    code: "MAT-2025018",
    name: "高强度包装带",
    specification: "PP材质",
    standard: "QB/T 2666-2004",
    current: "8卷",
    safety: "10卷",
    expectedArrival: "2025-06-09"
  },
  {
    code: "MAT-2025023",
    name: "热处理保护剂",
    specification: "高温型",
    standard: "YB/T 5072-2005",
    current: "25kg",
    safety: "20kg",
    expectedArrival: "-"
  }
]);

const notices = ref([
  {
    title: "安全生产培训通知",
    content: "下周三上午9点在培训室进行季度安全生产培训，请各部门安排人员参加。",
    date: "2025-06-01",
    type: "primary"
  },
  {
    title: "设备维护提醒",
    content: "搓丝机CS-12将于2025-06-07进行例行维护，请提前安排好生产计划。",
    date: "2025-06-02",
    type: "warning"
  },
  {
    title: "新订单通知",
    content: "收到浙江电子科技新订单，需要生产内六角圆柱头螺钉M6共20,000件，交货日期2025-06-20。",
    date: "2025-06-03",
    type: "secondary"
  },
  {
    title: "质量警报",
    content: "今日生产的高强度六角螺栓M12中，发现有5件头部裂纹不良品，已暂停该批次生产，请质检部门立即处理。",
    date: "2025-06-03",
    type: "danger"
  }
]);

const tasks = ref([
  {
    title: "处理热处理炉HT-300故障",
    description: "热处理炉HT-300出现温度异常，需要立即检修",
    dueDate: "2025-06-04",
    assignee: "王师傅",
    priority: "high",
    priorityText: "高优先级",
    completed: false
  },
  {
    title: "安排下周生产计划",
    description: "根据订单情况安排下周生产计划，确保产能平衡",
    dueDate: "2025-06-05",
    assignee: "张经理",
    priority: "medium",
    priorityText: "中优先级",
    completed: false
  },
  {
    title: "审核新产品工艺文件",
    description: "审核汽车零部件新产品的工艺文件和生产流程",
    dueDate: "2025-06-07",
    assignee: "李工程师",
    priority: "medium",
    priorityText: "中优先级",
    completed: false
  },
  {
    title: "整理本周生产数据",
    description: "整理本周生产数据，生成周报并提交给管理层",
    dueDate: "2025-06-08",
    assignee: "陈统计",
    priority: "low",
    priorityText: "低优先级",
    completed: true
  }
]);

// 计算属性
const filteredMaterials = computed(() => {
  if (inventoryView.value === "low") {
    return materials.value.filter(material => {
      const current = parseFloat(material.current);
      const safety = parseFloat(material.safety.replace("kg", "").replace("吨", "").replace("卷", ""));
      return current < safety * 1.2;
    });
  }
  return materials.value;
});

// 方法
const refreshData = () => {
  // 模拟数据刷新
  console.log("数据已刷新");
};

const exportReport = () => {
  // 模拟导出报告
  console.log("导出报告中...");
};

const setTrendPeriod = period => {
  trendPeriod.value = period;
  // 这里可以添加更新图表数据的逻辑
};

const setWorkOrderPeriod = period => {
  workOrderPeriod.value = period;
  // 这里可以添加更新工单数据的逻辑
};

const setInventoryView = view => {
  inventoryView.value = view;
};

const viewAllEquipment = () => {
  // 跳转到设备管理页面
  console.log("查看全部设备");
};

const viewAllWorkOrders = () => {
  // 跳转到工单管理页面
  console.log("查看全部工单");
};

const viewAllMaterials = () => {
  // 跳转到物料管理页面
  console.log("查看全部物料");
};

const viewAllNotices = () => {
  // 跳转到通知中心页面
  console.log("查看全部通知");
};

const viewAllTasks = () => {
  // 跳转到任务管理页面
  console.log("查看全部任务");
};

const createNewTask = () => {
  // 打开新建任务对话框
  console.log("创建新任务");
};

const toggleTaskCompletion = task => {
  task.completed = !task.completed;
};

const handleMaterialAction = material => {
  if (parseFloat(material.current) < parseFloat(material.safety.replace("kg", "").replace("吨", "").replace("卷", "")) * 1.2) {
    console.log("紧急采购", material);
  } else {
    console.log("查看详情", material);
  }
};

// 初始化图表
onMounted(() => {
  // 小图表初始化
  const createSmallChart = (id, data, color) => {
    const ctx = document.getElementById(id).getContext("2d");
    return new Chart(ctx, {
      type: "line",
      data: {
        labels: ["", "", "", "", "", "", ""],
        datasets: [
          {
            data: data,
            borderColor: color,
            backgroundColor: `${color}20`,
            tension: 0.4,
            fill: true,
            borderWidth: 2,
            pointRadius: 0
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
          x: { display: false },
          y: { display: false }
        },
        elements: { line: { tension: 0.4 } }
      }
    });
  };

  createSmallChart("chart1", [65, 59, 80, 81, 56, 85, 90], "#165DFF");
  createSmallChart("chart2", [78, 81, 75, 70, 65, 72, 82], "#FF9F43");
  createSmallChart("chart3", [95, 97, 96, 98, 97, 98, 98], "#36D399");
  createSmallChart("chart4", [65, 68, 70, 72, 75, 74, 76], "#00CFE8");

  // 产量趋势图表
  const productionTrendCtx = document.getElementById("productionTrendChart").getContext("2d");
  new Chart(productionTrendCtx, {
    type: "line",
    data: {
      labels: ["1月", "2月", "3月", "4月", "5月", "6月"],
      datasets: [
        {
          label: "实际产量",
          data: [25000, 28000, 26500, 30000, 29500, 32000],
          borderColor: "#165DFF",
          backgroundColor: "rgba(22, 93, 255, 0.1)",
          tension: 0.4,
          fill: true
        },
        {
          label: "目标产量",
          data: [24000, 27000, 26000, 29000, 28500, 31000],
          borderColor: "#36D399",
          borderDash: [5, 5],
          tension: 0.4,
          fill: false
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top",
          labels: {
            usePointStyle: true,
            boxWidth: 6
          }
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          }
        },
        y: {
          beginAtZero: false,
          ticks: {
            callback: function (value) {
              return value.toLocaleString();
            }
          }
        }
      }
    }
  });

  // 产品类别分布图表
  const productCategoryCtx = document.getElementById("productCategoryChart").getContext("2d");
  new Chart(productCategoryCtx, {
    type: "doughnut",
    data: {
      labels: ["螺栓", "螺母", "垫圈", "螺钉", "其他"],
      datasets: [
        {
          data: [35, 25, 15, 15, 10],
          backgroundColor: ["#165DFF", "#36D399", "#FF9F43", "#00CFE8", "#94A3B8"],
          borderWidth: 0,
          hoverOffset: 4
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "bottom",
          labels: {
            usePointStyle: true,
            boxWidth: 6,
            padding: 20
          }
        }
      },
      cutout: "70%"
    }
  });

  // 质量分析图表
  const qualityAnalysisCtx = document.getElementById("qualityAnalysisChart").getContext("2d");
  new Chart(qualityAnalysisCtx, {
    type: "bar",
    data: {
      labels: ["1月", "2月", "3月", "4月", "5月", "6月"],
      datasets: [
        {
          label: "合格率",
          data: [97.5, 97.8, 98.1, 98.0, 98.2, 98.3],
          backgroundColor: "#36D399",
          borderRadius: 4
        },
        {
          label: "返工率",
          data: [1.5, 1.4, 1.3, 1.2, 1.2, 1.2],
          backgroundColor: "#FF9F43",
          borderRadius: 4
        },
        {
          label: "报废率",
          data: [1.0, 0.8, 0.6, 0.8, 0.6, 0.5],
          backgroundColor: "#FF5C5C",
          borderRadius: 4
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top",
          labels: {
            usePointStyle: true,
            boxWidth: 6
          }
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          }
        },
        y: {
          beginAtZero: true,
          max: 100,
          ticks: {
            callback: function (value) {
              return value + "%";
            }
          }
        }
      }
    }
  });
});
</script>

<style scoped>
/* 保持原有的Tailwind配置 */

.content-auto {
  content-visibility: auto;
}
.scrollbar-hide::-webkit-scrollbar {
  display: none;
}
.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
.shadow-card {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
.bg-grid {
  background-image: linear-gradient(#e2e8f0 1px, transparent 1px), linear-gradient(to right, #e2e8f0 1px, transparent 1px);
  background-size: 20px 20px;
}
</style>
